package Serialization;

import java.io.*;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;

import org.jdom.*;
import org.jdom.input.*;
import org.jdom.output.*;

import Passager.Profil;
import Serveur.Serveur;
import Services.Repas;
import Services.ServiceChoisis;
import Services.TypeClasseTransport;
import Services.typeBillet;

import Client.Reservation;

public class ReservationXML {

	private Serveur serv;

	private static Element racine;	
	private static org.jdom.Document document;

	/**
	 * Constructeur créeant la racine et le document xml.
	 */
	public ReservationXML(Serveur serv)
	{
		this.serv=serv;
		racine = new Element("Reservation");	
		document = new Document(racine);
	}


	/**
	 * méthode pour enregistrer le fichier xml	
	 * @param document
	 * @param fichier
	 */

	public void enregistre(Document document, String fichier)
	{	
		try
		{
			XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());

			sortie.output(document, new FileOutputStream(fichier));
		}
		catch (java.io.IOException e){}
	}

	/** 
	 * méthode lire les fichiers xml deja créé 
	 * @param fichier
	 * @throws Exception
	 */


	public void lireFichier(String fichier) throws Exception
	{
		SAXBuilder sxb = new SAXBuilder();
		document = sxb.build(new File(fichier));
		racine = document.getRootElement();
	}

	/**
	 * créer le fichier xml
	 * @param reservation
	 */
	public void XmlReservation(Reservation reservation)
	{
		try
		{
			Element reservation1 = new Element("Reservation"+reservation.getIdReservation());
			racine.addContent(reservation1);

			Element idReservation = new Element ("idReservation");
			idReservation.setText(reservation.getIdReservation()+"");
			reservation1.addContent(idReservation);

			Element idTrajet = new Element ("IdTrajet");
			idTrajet .setText(reservation.getIdTrajet()+"");
			reservation1.addContent(idTrajet);

			Element date = new Element("Date");
			Element year = new Element("Year");
			Element month = new Element("Month");
			Element day = new Element("Day");
			Element hour = new Element("Hour");
			Element minute = new Element ("Minute");
			year.setText(reservation.getDate().get(GregorianCalendar.YEAR)+"");
			month.setText(reservation.getDate().get(GregorianCalendar.MONTH)+"");
			day.setText(reservation.getDate().get(GregorianCalendar.DAY_OF_MONTH)+"");
			hour.setText(reservation.getDate().get(GregorianCalendar.HOUR_OF_DAY)+"");
			minute.setText(reservation.getDate().get(GregorianCalendar.MINUTE)+"");
			date.addContent(year);
			date.addContent(month);
			date.addContent(day);
			date.addContent(hour);
			date.addContent(minute);
			reservation1.addContent(date);

			Element nbPersonne = new Element("NbrPersonne");
			String nbDePersonne = ""+reservation.getNbPersonne();
			nbPersonne.setText(nbDePersonne);
			reservation1.addContent(nbPersonne);

			Element idPassager = new Element("IdPassager");
			ArrayList<Integer> listePassager =  reservation.getListePassager();
			Iterator<Integer> i = listePassager.iterator();
			int e=0;
			while (i.hasNext())
			{
				e++;
				Integer iDPassagerTemp = i.next();
				Element idTemp = new Element ("ID"+e);
				idTemp.setText(iDPassagerTemp+"");
				idPassager.addContent(idTemp);				
			}	
			reservation1.addContent(idPassager);

			Element serviceChoisis = new Element ("ServicesChoisis");
			ArrayList<ServiceChoisis> listeService = reservation.getListeServiceChoisi();
			Iterator<ServiceChoisis> j = listeService.iterator();
			int counter = 0;
			while(j.hasNext())
			{
				counter++;
				ServiceChoisis serviceTemp = j.next();

				Element nbrNuit = new Element ("NbrNuit"+counter);
				Element typeClassTransport = new Element ("TypeClassTransport"+counter);
				Element profil = new Element ("Profil"+counter);
				Element repas = new Element ("Repas"+counter);
				Element typeBillet = new Element ("TypeBillet"+counter);

				nbrNuit.setText(serviceTemp.getNbNuite()+"");
				typeClassTransport.setText(serviceTemp.getClasseDuTransport().toString());
				profil.setText(serviceTemp.getProfilUtilisateur().toString());

				ArrayList<Repas> listeRepas = serviceTemp.getRepas();
				Iterator<Repas> k = listeRepas.iterator();
				int f = 0;
				while (k.hasNext())
				{
					f++;
					Element typeRepas = new Element("TypeRepas"+f);
					typeRepas.setText(k.next().toString());
					repas.addContent(typeRepas);
				}

				typeBillet.setText(serviceTemp.getBillet().toString());

				serviceChoisis.addContent(nbrNuit);
				serviceChoisis.addContent(typeClassTransport);
				serviceChoisis.addContent(profil);
				serviceChoisis.addContent(repas);
				serviceChoisis.addContent(typeBillet);
			}
			reservation1.addContent(serviceChoisis);

			enregistre(document,"Reservation.xml");	
		}  
		catch(Exception e){System.out.println("pb");};
	}

	public void XmlReservation(ArrayList<Reservation> listReservation)
	{
		clearXml();
		for(int i =0; i<listReservation.size();i++)
		{
			XmlReservation(listReservation.get(i));
		}
	}
	
	/**
	 * Supprimer les elements pre-existants du xml
	 */
	public void clearXml(){
		List listElements = racine.getChildren();
		ArrayList<Element> elements = new ArrayList<Element>();
		for (int i = 0; i<listElements.size(); i++)
		{
			//Element temp = (Element) listElements.get(i);
			elements.add((Element) listElements.get(i));
			//racine.removeChild(temp.getName());
		}
		for(Element aSupprimer : elements){
			racine.removeChild(aSupprimer.getName());
		}		
	}


	public ArrayList<Reservation> creatReservation()
	{
		try {
			this.lireFichier("Reservation.xml");
			List listReservation = racine.getChildren();
			ArrayList<Reservation> listeReservation = new ArrayList<Reservation> ();
			for (int i = 0; i<listReservation.size(); i++)
			{
				Element temp = (Element) listReservation.get(i);
				
				Integer idReservation = Integer.parseInt(temp.getChild("idReservation").getText());
				
				Integer idTrajet = Integer.parseInt(temp.getChild("IdTrajet").getText());
				
				Element date = (Element) temp.getChild("Date");
				Integer year= Integer.parseInt(date.getChild("Year").getText());
				Integer month= Integer.parseInt(date.getChild("Month").getText());
				Integer day= Integer.parseInt(date.getChild("Day").getText());
				Integer hour= Integer.parseInt(date.getChild("Hour").getText());
				Integer minute= Integer.parseInt(date.getChild("Minute").getText());
				GregorianCalendar dateGC = new GregorianCalendar (year,month,day,hour,minute);
				
				Integer nbrPersonne = Integer.parseInt( temp.getChild("NbrPersonne").getText());
				
				Element listIdPassager = (Element) temp.getChild("IdPassager");
				
				ArrayList<Integer> listePassager = new ArrayList<Integer> ();
				for(int j=1; j<=nbrPersonne; j++)
				{
					listePassager.add(Integer.parseInt(listIdPassager.getChild("ID"+j).getText()));
				}
				
				Element servicePassagertemp=(Element) temp.getChild("ServicesChoisis");
				ArrayList<ServiceChoisis> listeServiceChoisis = new ArrayList<ServiceChoisis> ();
				for (int j = 1 ; j<=nbrPersonne; j++)
				{
					Integer nbNuite = Integer.parseInt(servicePassagertemp.getChild("NbrNuit"+j).getText());
					TypeClasseTransport classeDuTransport = TypeClasseTransport.toProfil(
							servicePassagertemp.getChild("TypeClassTransport"+j).getText());
					Profil profilUtilisateur = Profil.toProfil(servicePassagertemp.getChild("Profil"+j).getText());
					ArrayList<Repas> repas = new ArrayList<Repas> ();
					Element repasTemp = (Element) servicePassagertemp.getChild("Repas"+j);
					List listTypeRepas = repasTemp.getChildren();
					Iterator k = listTypeRepas.iterator();
					while (k.hasNext())
					{
						Element courant = (Element) k.next();
						repas.add(Repas.toRepas(courant.getText()));
					}
					typeBillet billet = typeBillet.toProfil(servicePassagertemp.getChild("TypeBillet"+j).getText());
					ServiceChoisis serviceTemp = new ServiceChoisis(classeDuTransport, profilUtilisateur, repas, billet, nbNuite);
					listeServiceChoisis.add(serviceTemp);
				}
				Reservation reservation = new Reservation(serv, idTrajet, listePassager, listeServiceChoisis, idReservation, dateGC);
				listeReservation.add(reservation);
			}
			return listeReservation;
		} catch (Exception e) {System.out.println("pb2"); return null;}
	}
}